package se.peterbjorkman.android.trafikkamera.infodownload;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import se.peterbjorkman.android.trafikkamera.infodownload.IStatusReciever.Status;

import android.util.Log;

public class JSonDownloader {

	private static final String LOGTAG = JSonDownloader.class.getName();

	private IStatusReciever mStatusReciver = null;

	public JSONObject DownloadJSon(String url) throws DownloadException,
			JSONException {
		Log.d(LOGTAG, "In DownloadJSon url = " + url);

		String jsonString = null;
		try {
			final int timeoutSocket = 60000;
			final int timeoutConnection = 15000;

			setStatus(Status.Downloading);

			HttpGet request = new HttpGet(url);
			HttpParams httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters,
					timeoutConnection);
			HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

			HttpClient client = new DefaultHttpClient(httpParameters);
			HttpResponse response = client.execute(request);

			int status = response.getStatusLine().getStatusCode();

			if (status != HttpStatus.SC_OK) {
				String str = getHttpResonseString(response).trim();
				if (str.length() > 100)
					str = "";
				throw new DownloadException();// (url, status, str); TODO error message
			}

			ByteArrayOutputStream outStream = new ByteArrayOutputStream();

			response.getEntity().writeTo(outStream);

			jsonString = outStream.toString();
			setStatus(Status.Parsing);
			return new JSONObject(jsonString);

		} catch (IOException e1) {
			Log.e(LOGTAG, "IOException in DownloadJSon.");
			Log.e(LOGTAG, "Url: " + url);
			Log.e(LOGTAG, "IOException message: " + e1.getMessage());
			throw new DownloadException()/* TODO error message
										 * (url, ErrorCodes.IOError, e1)
										 */;
		}
	}

	public void SetStatusReciever(IStatusReciever reciver) {
		mStatusReciver = reciver;
	}

	private String getHttpResonseString(HttpResponse response)
			throws IOException, UnsupportedEncodingException {
		Log.d(LOGTAG, "In getHttpResonseString");
		InputStream content = response.getEntity().getContent();

		StringBuilder sb = new StringBuilder();
		String line;

		try {
			Header head = response.getEntity().getContentEncoding();
			BufferedReader reader;

			if (head != null)
				reader = new BufferedReader(new InputStreamReader(content, head
						.getName()));
			else
				reader = new BufferedReader(new InputStreamReader(content));

			while ((line = reader.readLine()) != null) {
				sb.append(line).append("\n");
			}
		} finally {
			content.close();
		}
		String str = sb.toString();
		return str;
	}

//	private void setStatus(Status status, int done, int total) {
//		if (mStatusReciver != null)
//			mStatusReciver.RecieveStatus(status, done, total);
//	}

	private void setStatus(Status status) {
		if (mStatusReciver != null)
			mStatusReciver.RecieveStatus(status);
	}
}
